<template>
  <div class="stat-container">
    <el-card class="stat-card">
      <template #header>
        <div class="card-header">
          <h2>发布的岗位统计</h2>
          <el-button type="primary" @click="refreshData" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </template>

      <!-- 总体统计卡片 -->
      <div class="overview-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-item" shadow="hover">
              <div class="stat-number">{{ stats.totalPositions || 0 }}</div>
              <div class="stat-label">发布岗位数</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-item" shadow="hover">
              <div class="stat-number">{{ stats.totalApplications || 0 }}</div>
              <div class="stat-label">总申请人数</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-item" shadow="hover">
              <div class="stat-number">{{ stats.totalSalaryPaid || 0 }}</div>
              <div class="stat-label">已发放工资(元)</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-item" shadow="hover">
              <div class="stat-number">{{ stats.salaryPaymentRate || '0%' }}</div>
              <div class="stat-label">工资发放率</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表展示 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <h4>岗位申请分布</h4>
              </template>
              <div ref="applicationChart" class="chart-container"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <h4>工资发放情况</h4>
              </template>
              <div ref="salaryChart" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getTeacherPositionStats } from '@/api/position'
import * as echarts from 'echarts'

const loading = ref(false)
const stats = ref({
  totalPositions: 0,
  totalApplications: 0,
  totalSalaryPaid: 0,
  salaryPaymentRate: '0%',
  positionDetails: []
})

const applicationChart = ref(null)
const salaryChart = ref(null)
let applicationChartInstance = null
let salaryChartInstance = null

// 获取统计数据
const fetchStats = async () => {
  loading.value = true
  try {
    const response = await getTeacherPositionStats()
    if (response.code === 0) {
      stats.value = response.data
      await nextTick()
      initCharts()
    } else {
      ElMessage.error(response.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据错误:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchStats()
}

// 获取进度条颜色
const getProgressColor = (rate) => {
  const percentage = parseFloat(rate)
  if (percentage >= 80) return '#67C23A'
  if (percentage >= 60) return '#E6A23C'
  if (percentage >= 40) return '#F56C6C'
  return '#909399'
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'ACTIVE': 'success',
    'INACTIVE': 'info',
    'CLOSED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文字
const getStatusText = (status) => {
  const statusMap = {
    'ACTIVE': '招聘中',
    'INACTIVE': '暂停',
    'CLOSED': '已结束'
  }
  return statusMap[status] || '未知'
}

// 初始化图表
const initCharts = () => {
  // 申请分布图表
  if (applicationChart.value) {
    applicationChartInstance = echarts.init(applicationChart.value)
    const applicationOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '岗位申请',
          type: 'pie',
          radius: '50%',
          data: stats.value.positionDetails?.map(item => ({
            name: item.positionName,
            value: item.applicationCount
          })) || []
        }
      ]
    }
    applicationChartInstance.setOption(applicationOption)
  }

  // 工资发放图表
  if (salaryChart.value) {
    salaryChartInstance = echarts.init(salaryChart.value)
    const salaryOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: stats.value.positionDetails?.map(item => item.positionName) || [],
        axisLabel: {
          interval: 0,
          rotate: 30,
          margin: 35,
          formatter: function(value) {
            return value.length > 7 ? value.slice(0, 7) + '\n' + value.slice(7) : value;
          },
          align: 'center'
        },
        axisTick: {
          alignWithLabel: true
        },
        boundaryGap: true
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}元'
        }
      },
      series: [
        {
          name: '总工资',
          type: 'bar',
          data: stats.value.positionDetails?.map(item => item.totalSalary) || []
        },
        {
          name: '已发放',
          type: 'bar',
          data: stats.value.positionDetails?.map(item => item.paidSalary) || []
        }
      ]
    }
    salaryChartInstance.setOption(salaryOption)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStats()
  
  // 监听窗口大小变化，重新调整图表
  window.addEventListener('resize', () => {
    if (applicationChartInstance) {
      applicationChartInstance.resize()
    }
    if (salaryChartInstance) {
      salaryChartInstance.resize()
    }
  })
})
</script>

<style scoped>
.stat-container {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.overview-stats {
  margin-bottom: 30px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.charts-section {
  margin-top: 30px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-card h4 {
  margin: 0;
  color: #303133;
}

.chart-container {
  height: 300px;
  width: 100%;
}

:deep(.el-progress-bar__outer) {
  background-color: #f0f0f0;
}

:deep(.el-progress-bar__inner) {
  transition: all 0.3s ease;
}
</style> 